﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:graphic/graphic.dart';
import '../../../core/models/heart_rate_model.dart' as api_models;

/// 心率详情页面
class HeartRateDetailView extends StatelessWidget {
  final String dailyValue;
  final List<api_models.HeartRateRecord> heartRateList;

  const HeartRateDetailView({
    super.key,
    required this.dailyValue,
    required this.heartRateList,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(
          '心率',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(
              children: [
                _buildHeartRateDisplay(),
                SizedBox(height: 20.h),
                _buildHeartRateZones(),
                SizedBox(height: 20.h),
                _buildHeartRateInfo(),
                SizedBox(height: 20.h),
                _buildRecentRecords(),
                SizedBox(height: 40.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建心率显示
  Widget _buildHeartRateDisplay() {
    // 计算平均心率
    final validRecords = heartRateList.where((record) => record.heartRate != null && record.heartRate! > 0).toList();
    final averageHeartRate = validRecords.isNotEmpty 
        ? (validRecords.map((r) => r.heartRate!).reduce((a, b) => a + b) / validRecords.length).round()
        : 0;

    // 获取最新记录的时间
    String timeInfo = '';
    if (heartRateList.isNotEmpty) {
      final latestRecord = heartRateList.first;
      if (latestRecord.endTime != null) {
        try {
          final endTime = DateTime.parse(latestRecord.endTime!);
          timeInfo = '${endTime.hour.toString().padLeft(2, '0')}:${endTime.minute.toString().padLeft(2, '0')}';
        } catch (e) {
          timeInfo = '最新测量';
        }
      }
    }

    return Column(
      children: [
        Text(
          '$averageHeartRate',
          style: TextStyle(
            fontSize: 64.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        Text(
          'BPM',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '$dailyValue, $timeInfo',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建心率区间
  Widget _buildHeartRateZones() {
    // 计算心率区间分布
    final validRecords = heartRateList.where((record) => record.heartRate != null && record.heartRate! > 0).toList();
    
    // 假设最大心率为220（220-年龄），这里使用180作为示例
    final maxHeartRate = 180;
    final zones = [
      {'name': '热身放松', 'min': (maxHeartRate * 0.5).round(), 'max': (maxHeartRate * 0.6).round(), 'color': const Color(0xFFFFD700)},
      {'name': '脂肪燃烧', 'min': (maxHeartRate * 0.6).round(), 'max': (maxHeartRate * 0.7).round(), 'color': const Color(0xFFFF6B35)},
      {'name': '心肺强化', 'min': (maxHeartRate * 0.7).round(), 'max': (maxHeartRate * 0.8).round(), 'color': const Color(0xFFFF4500)},
      {'name': '耐力强化', 'min': (maxHeartRate * 0.8).round(), 'max': (maxHeartRate * 0.9).round(), 'color': const Color(0xFFE91E63)},
      {'name': '无氧极限', 'min': (maxHeartRate * 0.9).round(), 'max': maxHeartRate, 'color': const Color(0xFF8B0000)},
    ];

    // 计算当前心率所在区间
    final averageHeartRate = validRecords.isNotEmpty 
        ? (validRecords.map((r) => r.heartRate!).reduce((a, b) => a + b) / validRecords.length).round()
        : 0;
    
    int currentZoneIndex = 0;
    for (int i = 0; i < zones.length; i++) {
      final min = zones[i]['min'] as int;
      final max = zones[i]['max'] as int;
      if (averageHeartRate >= min && averageHeartRate <= max) {
        currentZoneIndex = i;
        break;
      }
    }

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '心率区间',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.h),
          
          // 心率区间条
          Container(
            height: 20.h,
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: Stack(
              children: [
                Row(
                  children: zones.map((zone) {
                    return Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: zone['color'] as Color,
                          borderRadius: BorderRadius.circular(10.r),
                        ),
                      ),
                    );
                  }).toList(),
                ),
                // 当前心率指示器
                Positioned(
                  left: (averageHeartRate / maxHeartRate) * 100 - 10,
                  top: 0,
                  child: Container(
                    width: 20.w,
                    height: 20.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.black, width: 2.w),
                    ),
                    child: Icon(
                      Icons.favorite,
                      size: 12.sp,
                      color: Colors.red,
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 16.h),
          
          // 区间标签
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: zones.map((zone) {
              return Column(
                children: [
                  Text(
                    '${zone['min']}',
                    style: TextStyle(
                      fontSize: 10.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    zone['name'] as String,
                    style: TextStyle(
                      fontSize: 8.sp,
                      color: Colors.grey[400],
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 构建心率信息说明
  Widget _buildHeartRateInfo() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: Colors.red.withOpacity(0.3),
          width: 1.w,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '关于心率数据',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            '心率区间',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: Colors.red[300],
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '静息心率: 正常人在安静状态下每分钟心跳次数一般为 60-100次。',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.red[400],
              height: 1.5,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '运动心率: 运动过程中根据心率区间可以判断身体的运动状态, 选择合适的心率区间才能达到较佳的运动效果。',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.red[400],
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建最近记录图表
  Widget _buildRecentRecords() {
    final validRecords = heartRateList.where((record) => record.heartRate != null && record.heartRate! > 0).toList();
    
    if (validRecords.isEmpty) {
      return Container(
        height: 200.h,
        child: Center(
          child: Text(
            '暂无心率数据',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        ),
      );
    }

    // 取最近7次记录
    final recentRecords = validRecords.take(7).toList();
    final chartData = <Map<String, dynamic>>[];
    
    for (int i = 0; i < recentRecords.length; i++) {
      final record = recentRecords[i];
      chartData.add({
        'index': i,
        'heartRate': record.heartRate!,
      });
    }

    return Container(
      height: 200.h,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '最近${recentRecords.length}次记录',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.h),
          
          Expanded(
            child: Builder(
              builder: (context) => Chart(
                data: chartData,
                variables: {
                  'index': Variable(
                    accessor: (Map map) => map['index'] as num,
                  ),
                  'heartRate': Variable(
                    accessor: (Map map) => map['heartRate'] as num,
                  ),
                },
                marks: [
                  IntervalMark(
                    position: Varset('index') * Varset('heartRate'),
                    color: ColorEncode(
                      value: const Color(0xFFFFD700),
                    ),
                  ),
                ],
                coord: RectCoord(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
